// pages/member/member.js
const app = getApp();
const utils = require('../../utils/utils')
import { hexMD5 } from "../../utils/md5.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    value1: 0,
    columns: ['男', '女', ],
    show: false,
    shenri: false,
    fuwu: false,
    yinsi: false,
    CUSTOMER_SEX: '男',
    BIRTHDAY: '点击选择',
    USER_COUPON_PHONE: '',
    checked: false, //复选框
    //上传图片
    imgs: [],
    count: 1,
    avatar: '', //头像
    openid: '', //展示手机号
    phone: '', //手机号
    CUSTOMER_NAME: '',
    CUSTOMER_ADDRESS: '', //地址
    mobile: '',
    externalUserId: '', //二维码编号
    userId: '',
    userBrch: '',
    idCard: '', //展示身份证号
    shenfenk: false, //身份证框
    phone_shou: '', //后端传的手机号
    idCard_shen: '', //后端传的身份证号
    shi_q: true,
    shi_w: true,
    yuyue: [{
        id: 1,
        yujin: '0到5万'
      },
      {
        id: 2,
        yujin: '5到10万'
      },
      {
        id: 3,
        yujin: '10到50万'
      },
      {
        id: 4,
        yujin: '50万+'
      },
    ],

    yewu: [{
        id: 1,
        yujin: '存款'
      },
      {
        id: 2,
        yujin: '保险'
      }
    ],
    xuanye: '存款',
    yewuid:1,
    jinid: '',

    // 生日
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    CUSTOMER_ID:'',
    flag: true, //节流
  },


  



  // 开门红金额选择
  buttn_c(e) {
    console.log(e);
    console.log(e.currentTarget.dataset.item.id);
    console.log(e.currentTarget.dataset.item.yujin);
    this.setData({
      jinid: e.currentTarget.dataset.item.id,
      kmjine: e.currentTarget.dataset.item.yujin,

      shi_q: true
    })
  },


  buttn_d(e) {
    console.log(e);
    console.log(e.currentTarget.dataset.item.id);
    console.log(e.currentTarget.dataset.item.yujin);
    this.setData({
      yewuid: e.currentTarget.dataset.item.id,
      xuanye: e.currentTarget.dataset.item.yujin,
      shi_w: true
    })

  },



  xunakuangcu() {
    this.setData({

      shi_q: false
    })
  },


  yewuxuanze() {
    this.setData({

      shi_w: false
    })
  },






  blick() {
    wx.switchTab({
      url: '../../pages/personage/personage',
    })

  },


  //生日
  fromdata(value) {
    let sr_time = utils.formatDate(value.detail)
    console.log(sr_time);
    this.setData({
      BIRTHDAY: sr_time,
    });
  },
  //生日
  onInput(e) {
    console.log(111);
    console.log(e);
    console.log(e.detail);
    this.setData({
      currentDate: e.detail,
    });
  },

  shenri() {
    this.setData({
      shenri: !this.data.shenri
    })
  },



  //证件选框
  tanchu() {
    this.setData({
      show: !this.data.show
    })
  },

  onChange(e) {
    console.log(e.detail.value);
    this.setData({
      CUSTOMER_SEX: e.detail.value
    })
  },

  // 复选框
  fuxk(event) {
    console.log(event.detail);
    this.setData({
      checked: event.detail,
    });
  },

  fuwu() {
    // this.setData({ show: true });
    this.setData({
      fuwu: !this.data.fuwu
    })
  },

  yinsi() {
    // this.setData({ show: true });
    this.setData({
      yinsi: !this.data.yinsi
    })
  },

  //验证身份证

  idcardblur: function (e) {
    let idCard = e.detail.value;
    let reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;

    if (reg.test(idCard) == false) {
      this.setData({
        idCard: ''
      })
      wx.showToast({
        title: '身份证号码有误',
        icon: 'none',
        duration: 3000
      })
    } else {
      this.setData({
        idCard: idCard
      })
    }
  },

  //验证手机号
  // mobileInput(e) {
  //   let value = e.detail.value.replace(/\D/g, '')
  //   console.log(value);
  //   this.setData({
  //     mobile: value,
  //   })
  //   // var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(19[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
  //   var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(19[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
  //   if (this.data.mobile.length == 0) {
  //     wx.showToast({
  //       title: '输入的手机号为空，请重新输入！',
  //       icon: 'none',
  //       duration: 1500
  //     })
  //     this.setData({
  //       CUSTOMER_TEL: '',
  //       mobileFormat: false,
  //     })
  //   } else if (this.data.mobile.length < 11) {

  //     wx.showToast({
  //       title: '手机号长度有误，请重新输入！',
  //       icon: 'none',
  //       duration: 1500
  //     })
  //     this.setData({
  //       CUSTOMER_TEL: '',
  //       mobileFormat: false,
  //     })

  //   } else if (!myreg.test(this.data.mobile)) {
  //     wx.showToast({
  //       title: '手机号有误，请重新输入！',
  //       icon: 'none',
  //       duration: 1500
  //     })
  //     this.setData({
  //       CUSTOMER_TEL: '',
  //       mobileFormat: false,
  //     })

  //   } else {
  //     this.setData({
  //       mobileFormat: true,
  //     })
  //   }
  // },

  //上传头像
  // activation: function (e) {
  //   console.log(111);
  //   switch (this.data.imgs.length) {
  //     case 0:
  //       this.data.count = 1
  //       break
  //   }
  //   var that = this
  //   wx.chooseImage({
  //     count: that.data.count, // 默认3
  //     sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
  //     sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
  //     success: function (res) {
  //       console.log(res);
  //       console.log(res.tempFilePaths);
  //       // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
  //       var tempFilePaths = res.tempFilePaths
  //       for (var i = 0; i < tempFilePaths.length; i++) {
  //         //限制上传图片大小（4M）
  //         if (res.tempFiles[i].size > 4500000) {
  //           wx.showModal({
  //             content: '上传图片不能大于4M!',
  //             showCancel: false,
  //           });
  //           return false;
  //         } else {
  //           wx.uploadFile({
  //             url: app.globalData.interface+'/post/API_1165_uploadFileCOS',
  //             method: 'POST',
  //             name: "FIMG",
  //             filePath: tempFilePaths[i],
  //             header: {
  //               "content-type": "multipart/form-data"
  //             },
  //             success: function (res) {
  //               console.log(JSON.parse(res.data));
  //               let img_xi = JSON.parse(res.data)

  //               if (img_xi.result == 'success') {
  //                 wx.showToast({
  //                   title: "上传成功",
  //                   icon: "none",
  //                   duration: 1500
  //                 })

  //                 setTimeout(() => {
  //                   that.setData({
  //                     avatar: img_xi.newFile
  //                   })
  //                   console.log(that.data.avatar);
  //                 }, 1000);


  //               }
  //             },
  //             fail: function (err) {
  //               console.log(err);
  //               wx.showToast({
  //                 title: "上传失败",
  //                 icon: "none",
  //                 duration: 2000
  //               })
  //             },
  //             complete: function (result) {
  //               console.log(result.errMsg)
  //             }
  //           })
  //         }
  //       }
  //     }
  //   })
  // },


  tijiao() {


    if (this.data.flag) {

      this.data.flag = false







    console.log(hexMD5(this.data.openid));
    console.log(this.data.openid);


    if (this.data.checked == false) {
      wx.showToast({
        title: "请勾选用户协议",
        icon: "none",
        duration: 2000
      })

    } else if(this.data.externalUserId == undefined){

      console.log(this.data.phone);
      console.log(this.data.openid);
      console.log(this.data.idCard_shen);
      console.log(this.data.CUSTOMER_NAME);

      if (this.data.phone == '' || this.data.openid == '' || this.data.CUSTOMER_NAME == ''   ) {
        wx.showToast({
          title: "请完善信息",
          icon: "none",
          duration: 2000
        })
      } else {

        
        wx.request({
          url: app.globalData.interface+'/newVersion/API_2012_updateUser',
          method: 'POST',
          data: {

            // externalUserId:'wmCErvEAAABXml2pto2tdxe5i78HZ40Q',//二维码号
            externalUserId: this.data.externalUserId, //二维码号
            userBrch: this.data.userBrch,
            userId: this.data.userId,
            preMoney: this.data.jinid,
            preType:this.data.yewuid,// 业务选择id
            idCard: this.data.idCard, //省份证号
            CUSTOMER_TEL: this.data.phone,
            OPEN_ID: this.data.openid,
            BIRTHDAY: this.data.BIRTHDAY,
            CUSTOMER_NAME: this.data.CUSTOMER_NAME,
            CUSTOMER_IMG: this.data.avatar,
            CUSTOMER_SEX: this.data.CUSTOMER_SEX,
            CUSTOMER_ADDRESS: this.data.CUSTOMER_ADDRESS,
            KEY:'xianjgjKey9999',
            // OPEN_UUID: hexMD5(this.data.openid),
            OPEN_ID: this.data.OPEN_ID, //用户OPEN_ID
            session_key: this.data.session_key,
            OPEN_UUID: this.data.jiami
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: res => {

            console.log(res);
            console.log(res.data.result);
            if (res.data.result == 'success') {

              if (res.data.draw == true) {
                wx.navigateTo({
                  url: '../../pages/xkfetch/xkfetch',
                })
              } else {
                setTimeout(() => {
                  wx.switchTab({
                    url: '../../pages/personage/personage',
                  })
                }, 1000)
              }

              wx.showToast({
                title: "更新成功",
                icon: "none",
                duration: 2000
              })
            } else {
              wx.showToast({
                title: "更新失败",
                icon: "none",
                duration: 2000
              })
            }
          }
        })
      }

    }else{

                                                                                                                                                                               
      if (this.data.phone == '' || this.data.openid == '' || this.data.idCard == '' || this.data.CUSTOMER_NAME == ''|| this.data.yewuid == ''|| this.data.jinid == ''  ) {
        wx.showToast({
          title: "请完善信息",
          icon: "none",
          duration: 2000
        })
  
      } else {
        wx.request({
          url: app.globalData.interface+'/newVersion/API_2012_updateUser',
          method: 'POST',
          data: {

            // externalUserId:'wmCErvEAAABXml2pto2tdxe5i78HZ40Q',//二维码号
            externalUserId: this.data.externalUserId, //二维码号
            userBrch: this.data.userBrch,
            userId: this.data.userId,
            preMoney: this.data.jinid,
            preType:this.data.yewuid,// 业务选择id
            idCard: this.data.idCard, //省份证号
            CUSTOMER_TEL: this.data.phone,
            OPEN_ID: this.data.openid,
            BIRTHDAY: this.data.BIRTHDAY,
            CUSTOMER_NAME: this.data.CUSTOMER_NAME,
            CUSTOMER_IMG: this.data.avatar,
            CUSTOMER_SEX: this.data.CUSTOMER_SEX,
            CUSTOMER_ADDRESS: this.data.CUSTOMER_ADDRESS,
            // OPEN_UUID: hexMD5(this.data.openid),
            KEY:'xianjgjKey9999',
            OPEN_ID: this.data.OPEN_ID, //用户OPEN_ID
            session_key: this.data.session_key,
            OPEN_UUID: this.data.jiami
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: res => {

            console.log(res);
            console.log(res.data.result);
            if (res.data.result == 'success') {

              if (res.data.draw == true) {
                wx.navigateTo({
                  url: '../../pages/xkfetch/xkfetch',
                })
              } else {
                setTimeout(() => {
                  wx.switchTab({
                    url: '../../pages/personage/personage',
                  })
                }, 1000)
              }

              wx.showToast({
                title: "更新成功",
                icon: "none",
                duration: 2000
              })
            } else {
              wx.showToast({
                title: "更新失败",
                icon: "none",
                duration: 2000
              })
            }
          }
        })
      }
    }

    setTimeout(() => {
      console.log('-----------------',1);
      this.data.flag = true
    }, 3000)
  


  }
  },


  search() {
    wx.request({
      url: app.globalData.interface+'/newVersion/API_2010_selectUserSome',
      method: 'POST',
      data: {
        OPEN_ID: this.data.openid,
        CUSTOMER_ID: this.data.CUSTOMER_ID,
        OPEN_ID: this.data.openid, //用户OPEN_ID
        session_key: this.data.session_key,
        OPEN_UUID: this.data.jiami
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        console.log(res.data);
        console.log(res);
        // if (res.data.data != null) {
          this.setData({
            CUSTOMER_ID: res.data.data.CUSTOMER_ID,
            CUSTOMER_TEL: res.data.data.phone,
            BIRTHDAY: res.data.data.BIRTHDAY,
            CUSTOMER_NAME: res.data.data.CUSTOMER_NAME,
            avatar: res.data.data.CUSTOMER_IMG,
            CUSTOMER_SEX: res.data.data.CUSTOMER_SEX,
            CUSTOMER_ADDRESS: res.data.data.CUSTOMER_ADDRESS,
          })
          // if (res.data.data.IDCARD == '' || res.data.data.externalUserId == '') {
          //   this.setData({
          //     shenfenk:true
          //   })
          // }
        // } else {
        //   this.setData({
        //     shenfenk: false
        //   })
        // }
      }
    })
  },


  //获取手机号
  getPhoneNumber(e) {
    console.log(e);
    // console.log(e.detail.code)
    this.setData({
      code: e.detail.code
    })
    wx.request({
      url: app.globalData.interface+'/post/API_1032_getWeiXinPhone',
      method: 'GET',
      //向后端发送的数据
      data: {
        code: this.data.code,
        OPEN_ID: this.data.openid, //用户OPEN_ID
        session_key: this.data.session_key,
        OPEN_UUID: this.data.jiami //将code发送到后台服务器。
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded" //POST方式是这个
      },
      success: res => {
        console.log(res);
        console.log(res.data.phone);
        if (res.data.result != 'success') {
          wx.showToast({
            title: '获取手机号失败',
            duration: 1000,
            icon: 'error',
          })
        } else {

          var phone = res.data.phone;
          app.globalData.phone = phone;

          this.setData({
            phone: res.data.phone,
            Getphone: true,
          })

          // if (this.data.externalUserId != '') {


          // }
          // this.chaxunshen()//查询手机号
          this.baocunphone() //保存手机号接口
          // wx.navigateTo({
          //   url: '../../pages/qliebiao/qliebiao?data=' + JSON.stringify(this.data.phone)
          // })

        }
      }
    })
  },



  // 判断是否授权
  scanCod() {
    var that = this
    wx.request({
      url: app.globalData.interface+'/newVersion/API_2007_getPhoneByOpenId',
      method: 'POST',
      //向后端发送的数据
      data: {
        OPEN_ID: this.data.openid,
        OPEN_ID: this.data.openid, //用户OPEN_ID
        session_key: this.data.session_key,
        OPEN_UUID: this.data.jiami //将code发送到后台服务器。
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded" //POST方式是这个
      },
      success: res => {
        console.log(res);
        console.log(res.data.data.CUSTOMER_TEL);
        if (res.data.result != 'success') {
          wx.showToast({
            title: '请获取手机号',
            duration: 1000
          })
          that.setData({
            Getphone: false,
          })
        } else {

          var Integral = res.data.data.INTEGRAL;
          app.globalData.Integral = Integral;
          console.log(res.data.data.IDCARD);
          that.setData({
            CUSTOMER_ID:res.data.data.CUSTOMER_ID,
            INTEGRAL: res.data.data.INTEGRAL,
            LEVEL_IMG: res.data.data.LEVEL_IMG,
            // phone: phone,
            // idCard: IDCARD,
            Getphone: true,
            phone: res.data.data.CUSTOMER_TEL,
            idCard: res.data.data.IDCARD
          })

        }
      }
    })
  },

  baocunphone() {
    wx.request({
      url: app.globalData.interface+'/newVersion/API_2011_savePhoneAndOpenId',
      method: 'POST',
      //向后端发送的数据
      data: {
        CUSTOMER_TEL: this.data.phone,
        OPEN_ID: this.data.openid,
        KEY:'xianjgjKey9999',
        OPEN_ID: this.data.openid, //用户OPEN_ID
        session_key: this.data.session_key,
        OPEN_UUID: this.data.jiami
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded" //POST方式是这个
      },
      success: res => {
        console.log(res);
      }
    })
  },


  chaxunshen() {
    console.log(this.data.externalUserId);
    console.log(this.data.phone);
    console.log(this.data.openid);
    wx.request({
      url: app.globalData.interface+'/newVersion/API_2061_getGradeByPhone',
      method: 'POST',
      //向后端发送的数据
      data: {
        // externalUserId: 'wmCErvEAAABXml2pto2tdxe5i78HZ40Q',
        externalUserId: this.data.externalUserId,
        // userBrch: this.data.userBrch,
        // userId: this.data.userId,
        // preMoney: this.data.jinid,
        mobile: this.data.phone,
        openId: this.data.openid,
        OPEN_ID: this.data.openid, //用户OPEN_ID
        session_key: this.data.session_key,
        OPEN_UUID: this.data.jiami
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded" //POST方式是这个
      },
      success: res => {

        if (res.data.code == 'success') {
          console.log(res.data.idCard);
          this.setData({
            idCard: res.data.idCard
          })
        } else {
          wx.showModal({
            title: '温馨提示',
            content: '该手机未查到信息',
            success: function (res) {
              if (res.confirm) { //这里是点击了确定以后
                console.log('用户点击确定')
                // wx.switchTab({
                //   url: '../../pages/Information/Information',
                // })
              } else { //这里是点击了取消以后
                console.log('用户点击取消')
                // wx.switchTab({
                //   url: '../../pages/Information/Information',
                // })
              }
            }
          })
        }
      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e) {
    console.log(e.q);
    console.log(e);
    if (e.q != undefined) {
      let s = e.q

      let externalUserId = s.indexOf('Id%3D')
      let str_new = s.substring(externalUserId + 5, )
      let external = str_new.match(/(\S*)%26userId/)[1];
      let userId = str_new.match(/userId%3D(\S*)%26userBrch/)[1];
      let userBrch = str_new.match(/userBrch%3D(\S*)/)[1];

      console.log(str_new);
      console.log(external);
      console.log(userId);
      console.log(userBrch);
      this.setData({
        externalUserId: external,
        userBrch: userBrch,
        userId: userId,
      })
    } else {
      this.setData({
        externalUserId: e.q,
        shenfenk: true, //身份证框
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  

    this.setData({
      CUSTOMER_ID: app.globalData.CUSTOMER_ID,
      jiami: app.globalData.jiami,
      OPEN_ID: app.globalData.openid,
      openid: app.globalData.openid,
      session_key: app.globalData.session_key,
    })

    var that = this



 if (that.data.jiami == '' || that.data.session_key == '') {

    wx.login({
      success: function (res) {
        console.log(res);
        if (res.code) { //wx.login获取code。
          console.log(res.code);
          //发起网络请求
          wx.request({
            url: app.globalData.interface+'/post/API_1062_appGetOpenid',
            method: 'GET',
            //向后端发送的数据
            data: {
              code: res.code //将code发送到后台服务器。
            },
            header: {
              "Content-Type": "application/x-www-form-urlencoded" //POST方式是这个
            },
            success: res => {
              console.log(res);
              if (res.data.result == 'success') {
                console.log(res.data.openid);
                that.setData({
                  openid: res.data.openid,
                  CUSTOMER_ID: app.globalData.CUSTOMER_ID
                })
                that.scanCod()
                that.search()
              }
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });

  }else{

    console.log('成功');
    that.scanCod()
    that.search()
  }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})